/*
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//                  佛祖保佑             永无BUG
-------by 你猜
*/

import UIKit
import SnapKit
import MJRefresh


class CZPushViewController: UIViewController , UITableViewDataSource,CZPushBottomViewDelegate, UITableViewDelegate
{
    
    //MARK:-- 属性
    var status: CZStatus?
    
    var commentes: [CZcommentModel]? {
        didSet{
            //            print("hahahahahba\(commentes)")
            self.tableView.reloadData()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //        print("---\(status) ")
        tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewComment")
        
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadMoreComment")
        //        tableView.estimatedSectionHeaderHeight = 10
        
        loadNewComment()
        title = "微博详情"
        prepareUI()
        view.backgroundColor = UIColor(white: 0.7, alpha: 1)
        
        tableView.mj_header.beginRefreshing()
    }
    
    func loadMoreComment(){
        
        // TODO: 尾部刷新
        var max_id = 0
        let since_id = 0
        if  (commentes != nil) {
            
            max_id = commentes?.last?.id ?? 0
            if max_id != 0 {
                max_id = max_id - 1
            }
        }
        
        CZcommentModel.loadcommentData(since_id, max_id: max_id, statuId: (status?.id)!) { ( commentData, error) -> () in
            
            if error != nil {
                
                return
            }
             guard let res = commentData else{
                print("出错")
                return
            }
            if res.count == 0 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
                return
            }
            
            print("res=== \(res)")
            if self.commentes != nil{
                self.commentes = self.commentes! + res
            }
            else{
                self.commentes = res
                
            }
            if (self.tableView.mj_header != nil) {
                
                self.tableView.mj_footer.endRefreshing()
            }
            self.tableView.reloadData()
            
        }
    }
    
    //加载数据
    func loadNewComment() {
        
        var since_id = 0
        let max_id = 0
        
        /// 刷新情况
        if  (commentes != nil) {
            
            since_id = commentes?.first?.id ?? 0
            
        }
        
        //        print("since_id \(since_id)")
        
        CZcommentModel.loadcommentData(since_id, max_id: max_id, statuId: (status?.id)!) { ( commentData, error) -> () in
            
            if error != nil {
                
                return
            }
            
            if commentData != nil {
                
                print("commentData=== \(commentData)")
                if self.commentes != nil{
                    self.commentes = commentData! + self.commentes!
                }
                else{
                    self.commentes = commentData
                    
                }
                if (self.tableView.mj_header != nil) {
                    
                    self.tableView.mj_header.endRefreshing()
                }
                self.tableView.reloadData()
            }
        }
    }
    
    
    // 添加底部视图
    func setupPushBottomView()
    {
        view.addSubview(pushBottomView)
        
        pushBottomView.translatesAutoresizingMaskIntoConstraints = false
        // 添加约束
        view.addConstraint(NSLayoutConstraint(item: pushBottomView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: pushBottomView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: pushBottomView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 44))
        view.addConstraint(NSLayoutConstraint(item: pushBottomView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        let animation = CABasicAnimation(keyPath: "transform.rotation.y")
        animation.fromValue = (-M_PI)
        animation.removedOnCompletion = false
        animation.fillMode = kCAFillModeForwards;
        animation.duration = 1.0;
        self.view.layer.addAnimation(animation, forKey: nil);
        
        // 添加底部视图
        setupPushBottomView()
    }
    
    func prepareUI (){
        self.view .addSubview(tableView)
        
        tableView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0))
        }
    }
    
    //数据源方法
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return  2;
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if  section == 0 {
            
            return  1;
        }else if section == 1 {
            
            print("commentes?.count\(commentes?.count)")
            
            return commentes?.count ?? 0
        }
        return 0
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            print("status!.cellID \(status!.cellID())")
            
            let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellID()) as! CZStatusCell
            
            cell.bottomView.backgroundColor = UIColor(white: 0.98, alpha: 1)
            cell.bottomView.status = status
            
            weak var weakSelf = self
            
            if status!.cellID() == "StatusForwardCell" {
                let fwcell = cell as! CZStatusForwardCell
                
                fwcell.value = {(status: CZStatus) -> Void in
                    weakSelf!.pushContronler(status);
                }
            }
            else{
                
            }
            cell.status = status
            return cell
        } else {
            let cell = tableView.dequeueReusableCellWithIdentifier("commentCell") as! CZTableViewCell_JC
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            if commentes == nil {
                cell.comments = nil
            }
            else{
                
                let comments = commentes! [indexPath.row]
                cell.comments = comments
            }
            return cell
        }
    }
    
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        var rotation =  CATransform3D()
        rotation = CATransform3DMakeRotation(CGFloat (90.0*M_PI) / CGFloat (180), 0.0, 0.7, 0.4);
        rotation.m34 = 1.0 / -600;
        
        cell.layer.shadowColor = UIColor.blueColor().CGColor
        cell.layer.shadowOffset = CGSizeMake(10, 10);
        cell.alpha = 0;
        cell.layer.transform = rotation;
        cell.layer.anchorPoint = CGPointMake(0, 0.5);
        
        UIView.beginAnimations("rotation", context: nil);
        UIView .setAnimationDuration(0.8)
        cell.layer.transform = CATransform3DIdentity;
        cell.alpha = 1;
        cell.layer.shadowOffset = CGSizeMake(0, 0);
        UIView.commitAnimations()
    }
    
    //跳转界面
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        
        if indexPath.section == 0 {
            
            if status?.cellID() == "StatusForwardCell" {
                
                pushContronler(status!)
            }
        }
    }
    
    func pushContronler(status: CZStatus) {
        
        let pushVc = CZPushViewController()
        pushVc.status = status;
        pushVc.hidesBottomBarWhenPushed  = true
        navigationController?.pushViewController(pushVc, animated: false)
        
        
    }
    
    //组高
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if(section==1) {
            return 40
        }
        return 10
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 10
        }else {
            return 0
        }
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if(section==1) {
            
            let headview = HPlikeHeadView(frame: CGRect(x: 0, y: 0, width: 375, height: 40))
            return headview
        }
        return nil
    }
    
    //懒加载
    lazy var tableView: UITableView = {
        let tableView = UITableView()
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.dataSource = self
        tableView.delegate = self
        
        tableView.tableFooterView?.hidden = true
        
        // 注册原创cell
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusNormalCell.rawValue)
        // 注册转发cell
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusForwardCell.rawValue)
        
        tableView.registerClass(CZTableViewCell_JC.self, forCellReuseIdentifier: "commentCell")
        
        return tableView
    }()
    
    // MARK: - 懒加载底部按钮视图
    private lazy var pushBottomView: CZPushBottomView =
    {
        let pushBottomView = CZPushBottomView()
        
        // 指定代理
        pushBottomView.delegate = self
        
        return pushBottomView
        
    }()
    
    
    // MARK: -CZPushBottomViewDelegate代理方法
    // 转发
    func pushBottomViewForwardButtonDidClick(btn: UIButton)
    {
        // modal出控制器
        // 创建控制器
        let forwardVC = CZPushForwardViewController()
        forwardVC.status = status
        let title = btn.titleLabel!.text
        forwardVC.navigationItem.title = title! + "微博"
        let nav = UINavigationController(rootViewController: forwardVC)
        presentViewController(nav, animated: false) { () -> Void in
            // 将微博模型传过去
            // 获得当前微博模型
        }
    }
    
    // 评论
    func pushBottomViewCommentButtonDidClick(btn: UIButton)
    {
        // modal出控制器
        // 创建控制器
        let commentVC = CZPushCommentViewController()
        let title = btn.titleLabel!.text
        commentVC.navigationItem.title = title! + "微博"
        let nav = UINavigationController(rootViewController: commentVC)
        presentViewController(nav, animated: false) { () -> Void in
            // 将微控制器传过去
            commentVC.vc = self
        }
        
    }
    
    // 赞
    func pushBottomViewLikeButtonDidClick(btn: UIButton)
    {
        btn.imageView!.transform = CGAffineTransformMakeScale(0.5, 0.5)
        UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            btn.setImage(UIImage(named: "timeline_icon_like"), forState: UIControlState.Normal)
            btn.imageView!.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
                btn.setImage(UIImage(named: "timeline_icon_unlike"), forState: UIControlState.Selected)
                
                let cell = self.tableView .dequeueReusableCellWithIdentifier(self.status!.cellID()) as! CZStatusCell
                cell.bottomView.status?.attitudes_count =  self.status!.attitudes_count + 1
                self.tableView.reloadData()
        }
    }
}

